﻿$(function () {

    function LoginModel() {

        this.FirstInFlag = "1";
        this.Register_ad = "";
        this.PopFlag = "0";
        this.NeedImgCodeIp = "0";
        this.NeedImgCodeAccount = "0";
        this.ReturnUrl = "";
        this.From = "";
        this.HomeUrl = "www.benlai.com";
        this.CallBack = function () { };
        this.SuccessFunc = null;
        this.AliyunRiskRecognition = "0";
        this.showPage = function (popFlag) {
            var that = this;
            if (popFlag && popFlag == "1") {
                that.PopFlag = popFlag;
            }
            $.BENLAI.tmpl({
                dom: $("#LoginTmpl"), v: "url:/Account/Login.html", datas: that, callback: function () {
                    if (that.FirstInFlag == "1") {
                        that.FirstInFlag = "0"; 
                        //读cookie
                        var cookie = window.Cookies("ZDCustomerLogin").val();
                        if (cookie != null) {
                            var path = cookie.split(','); //用户名cookie信息
                            if (path.length >0) {
                                $("#accountTxt").val(path[0]);
                            }

                        }
                    }
                    if (that.AliyunRiskRecognition == "1") {
                        pointman.use('do', function () {
                        var afs = pointman.getConfig();
                        var afs_appkey = afs.appkey;
                        var afs_scene = afs.scene;
                        var afs_token = afs.token;
                        document.getElementById('afs_scene').value = afs_scene;
                        document.getElementById('afs_token').value = afs_token;
                    });
                   }
                }
            });
            var dt = new Date();
            dt.setMonth(dt.getMonth() + 1);
            document.cookie = "uuklr=" + this.newGuid() + ";path=/;expires=" + dt.toUTCString();
        };
        this.newGuid = function () {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "-";
            }
            return guid;
        };
        this.showExceptionAccount = function (phoneShow, token, message, phoneFirstFlag, score, callBack) {
            $.BENLAI.ExceptionAccountModel.showPage(phoneShow, token, message, phoneFirstFlag, score, callBack);
        };

        return this;
    }

    $("#LoginTmpl").CreateController({

        events: {
            "#accountTxt blur": "accountValidateAjax",
            "#imgCodeTxt blur": "imgCodeValidate",
            "#passTxt blur": "passValidate",
            "#loginBtn click": "loginSubmit",
            "#checkboxUserRegisterContentPage click": "remeberUser",
            "#imgCodeBtn click": "GetVryImgGen",
            "#registerClose click": "closeLogin",
            "#accountTxt keyup": "EnterClick",
            "#imgCodeTxt keyup": "EnterClick",
            "#passTxt keyup": "EnterClick",
            "#tenWeiboBtn click": "tenWeiboSub"
        },
        init: function () {
            var loginModel = new LoginModel();
            $.BENLAI.LoginModel = loginModel;

            this.focusInit();
            //var url = (('https:' == document.location.protocol ? 'https://' : 'http://') + 'mat1.gtimg.com/app/openjs/openjs.js');
            //loadScript(url, function () {
            //    T.init({ appkey: 801348101 });
            //});

        },
        GetVryImgGen: function () {
            $("#imgCodeImg").attr('src', '/Account/GetVryImgGen?' + Math.round(Math.random() * 10000));
        },
        focusInit: function () {
            var tmp = $("#LoginTmpl");
            tmp.delegate("#accountTxt", "focus", function () {
                if (this.value == "请输入邮箱/手机") {
                    this.value = "";
                }
            });

            tmp.delegate("#imgCodeTxt", "focus", function () {
                if (this.value == "请输入验证码") {
                    this.value = "";
                }
            });

        },
        accountValidate: function () {
            var type = "account";
            var txt = document.getElementById(type + "Txt").value;
            if(txt && txt.length>0){
                txt = $.trim(txt);
                document.getElementById(type + "Txt").value = txt;
            }
            if (txt.length == 0 || txt == "请输入邮箱/手机") {
                document.getElementById(type + "Mes").innerHTML = "请输入邮箱/手机";
                var flag = $("dl[data-type=" + type + "]>s");
                flag.removeClass("yes");
                flag.addClass("no");
                return false;
            }
            else {
                var p = /^1[34578][0-9]{9}$/;
                var e = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                if (!p.test(txt) && !e.test(txt)) {
                    document.getElementById(type + "Mes").innerHTML = "账号格式不正确，请重新输入！";
                    var flag = $("dl[data-type=" + type + "]>s");
                    flag.removeClass("yes");
                    flag.addClass("no");
                    return false;
                }
                else {
                    document.getElementById(type + "Mes").innerHTML = "";
                    var flag = $("dl[data-type=" + type + "]>s");
                    flag.removeClass("no");
                    flag.addClass("yes");
                    return true;
                }
            }
        },
        accountValidateAjax: function () {
            var that = this;
            if (that.accountValidate()) {
                var loginModel = $.BENLAI.LoginModel;
                if (loginModel.NeedImgCodeIp != "1") {
                    var account = $("#accountTxt").val();
                    var pwd = $("#passTxt").val();
                    $.BENLAI.ajax({
                        type: "POST",
                        url: "/Account/ValidateAccountNeedImgCode",
                        data: {
                            account: account
                        },
                        async: true,
                        success: function (data) {
                            if (data.error == "1") {
                                if (loginModel.NeedImgCodeAccount != "1") {
                                    loginModel.NeedImgCodeAccount = "1";
                                    loginModel.showPage();
                                    $("#accountTxt").val(account);
                                    $("#passTxt").val(pwd);
                                    that.GetVryImgGen();
                                }
                            }else if (data.error == "2" && data.msg) {
                                document.getElementById("accountMes").innerHTML = data.msg;
                            }
                            else {
                                if (loginModel.NeedImgCodeAccount == "1") {
                                    loginModel.NeedImgCodeAccount = "0";
                                    loginModel.showPage();
                                    $("#accountTxt").val(account);
                                    $("#passTxt").val(pwd);
                                }
                            }
                        },
                        error: function () {
                        }
                    });
                }
            }
        },
        imgCodeValidate: function () {
            var type = "imgCode";
            var txt = document.getElementById(type + "Txt").value;
            if (txt.length == 0 || txt == "请输入验证码") {
                document.getElementById(type + "Mes").innerHTML = "请输入验证码!";
                return false;
            }
            else {
                document.getElementById(type + "Mes").innerHTML = "";
                return true;
            }
        },
        passValidate: function () {
            var type = "pass";
            var txt = document.getElementById(type + "Txt").value;
            document.getElementById(type + "Mes").innerHTML = "";
            if (txt.length == 0 || txt == "请输入密码") {
                document.getElementById(type + "Mes").innerHTML = "请输入密码!";
                var flag = $("dl[data-type=" + type + "]>s");
                flag.removeClass("yes");
                flag.addClass("no");
                return false;
            }
            else if (txt.length < 6 || txt.length > 16) {
                document.getElementById(type + "Mes").innerHTML = "密码至少6位，最多16位!";
                var flag = $("dl[data-type=" + type + "]>s");
                flag.removeClass("yes");
                flag.addClass("no");
                return false;
            }
            else {
                document.getElementById(type + "Mes").innerHTML = "";
                var flag = $("dl[data-type=" + type + "]>s");
                flag.removeClass("no");
                flag.addClass("yes");
                return true;
            }
        },
        remeberUser: function () {
            if ($("#checkboxUserRegisterContentPage").attr("checked") == true) {
                $("#txtJiZhuUserPass1").val("1");
                $("#txtJiZhuUser1").val("1");
            } else {
                $("#txtJiZhuUserPass1").val("0");
                $("#txtJiZhuUser1").val("0");
            }
        },
        loginSubmit: function () {
            var loginModel = $.BENLAI.LoginModel;
            var popFlag = false;
            if(loginModel && loginModel.PopFlag && loginModel.PopFlag=="1"){
                popFlag = true;
            }
            var imageCodeNeed = false;
            if (this.accountValidate() && this.passValidate()) {
                var Errorid = "#passMes";
                if ("1" == loginModel.NeedImgCodeIp || "1" == loginModel.NeedImgCodeAccount) {
                    imageCodeNeed = true;
                    Errorid = "#imgCodeMes";
                    if (!this.imgCodeValidate()) {
                        return false
                    }
                }

                var that = this;
                $.BENLAI.ajax({
                    type: "POST",
                    url: "/Account/Login?r="+ Math.round(Math.random() * 10000),
                    data: $("#formLogin").serialize(),
                    success: function (result) {
                        if (AjaxValidate(result)) {
                            if (result != null) {
                                var message = result.msg;
                                var error = result.error;
                                var data = result.data;
                                var retrurnUrl = data ? data.ReturnUrl : "";
                                var pwd = $("#passTxt").val();
                                var account = $("#accountTxt").val();
                                if (error == "0") {
                                    var bindPhoneModel = $.BENLAI.BindPhoneModel;
                                    if (popFlag) {
                                        bindPhoneModel.CallBack = function () {
                                            if (loginModel.SuccessFunc) {
                                                that.closeLogin();
                                                loginModel.SuccessFunc();
                                            }
                                            else
                                                window.location.href = window.location.href;
                                            return false;
                                        };
                                    }
                                    else {
                                        bindPhoneModel.CallBack = function () {
                                            if (retrurnUrl) {
                                                window.location.href = decodeURIComponent(retrurnUrl);
                                                return false;
                                            } else {
                                                window.location.href = getLocationHref("/");
                                                return false;
                                            }
                                        };
                                    }
                                    that.LoginSuccess(data, popFlag);
                                } else if (error == "8") {
                                    var accountTemp = $("#accountTxt").val();
                                    var pwdTemp = $("#passTxt").val();
                                    loginModel.NeedImgCodeAccount = "1";
                                    loginModel.showPage();
                                    $("#accountTxt").val(accountTemp);
                                    $("#passTxt").val(pwdTemp);
                                    that.GetVryImgGen();
                                    var imageCodeMesObj = $("#imgCodeMes");
                                    if (imageCodeMesObj)
                                        imageCodeMesObj.html(message);
                                    else
                                        $(Errorid).html(message);
                                } else if (error == "7") {
                                    if (loginModel.NeedImgCodeAccount != "1")
                                    {
                                        loginModel.NeedImgCodeAccount = "1";
                                        loginModel.showPage();
                                        $("#accountTxt").val(account);
                                        $("#passTxt").val(pwd);
                                        that.GetVryImgGen();
                                        var imageCodeMesObj = $("#imgCodeMes");
                                        if (imageCodeMesObj)
                                            imageCodeMesObj.html(message);
                                        else
                                            $(Errorid).html(message);
                                    } else {
                                        if (imageCodeNeed) {
                                            that.GetVryImgGen();
                                        }
                                        $(Errorid).html(message);
                                    }

                                } else if (error == "6" || error == "2") {
                                    if (imageCodeNeed) {
                                        that.GetVryImgGen();
                                    }
                                    $("#passMes").html(message);
                                } else if (error == "3") {
                                    if (imageCodeNeed) {
                                        that.GetVryImgGen();
                                    }
                                    $("#accountMes").html(message);
                                } else if (error == "1" || error == "5") {
                                    if (imageCodeNeed) {
                                        that.GetVryImgGen();
                                    }
                                    $(Errorid).html(message);
                                    return false;
                                } else if (error == "10" || error == "11" || error == "12" || error == "13" || error == "14" || error == "16") {
                                    var phoneShow = "";
                                    if (data && data.PhoneShow)
                                        phoneShow = data.PhoneShow;
                                    var exceptionCallback = function () { };
                                    if (popFlag) {
                                        exceptionCallback = function () {
                                            if (loginModel.SuccessFunc) {
                                                that.closeLogin();
                                                loginModel.SuccessFunc();
                                            }
                                            else
                                                window.location.href = window.location.href;
                                            return false;
                                        };
                                    }
                                    else {
                                        exceptionCallback = function () {
                                            if (retrurnUrl) {
                                                window.location.href = decodeURIComponent(retrurnUrl);
                                                return false;
                                            } else {
                                                window.location.href = getLocationHref("/");
                                                return false;
                                            }
                                        };
                                    }
                                    loginModel.showExceptionAccount(phoneShow, "", "", data.PhoneFirstFlag, data.Score, exceptionCallback);

                                    return false;
                                } else if (error == "15") {
                                    var token = "";
                                    if (data && data.Token)
                                        token = data.Token;
                                    var exceptionCallback = function () { };
                                    if (popFlag) {
                                        exceptionCallback = function () {
                                            if (loginModel.SuccessFunc) {
                                                that.closeLogin();
                                                loginModel.SuccessFunc();
                                            }
                                            else
                                                window.location.href = window.location.href;
                                            return false;
                                        };
                                    }
                                    else {
                                        exceptionCallback = function () {
                                            if (retrurnUrl) {
                                                window.location.href = decodeURIComponent(retrurnUrl);
                                                return false;
                                            } else {
                                                window.location.href = getLocationHref("/");
                                                return false;
                                            }
                                        };
                                    }
                                    loginModel.showExceptionAccount("", token, "",false,0,exceptionCallback);
                                    return false;
                                } else {
                                    if (message.length > 0)
                                        $(Errorid).html(message);
                                    else
                                        $(Errorid).html("登录出现了错误");
                                    return false;
                                }

                            }
                        }
                    },
                    error: function () {
                        $(Errorid).html("登录出现了错误");
                        return false;
                    }
                });

            }
        },
        //回车
        EnterClick: function (event, type) {
            var key = 0;
            if (window.event) {
                key = window.event.keyCode;
            } else {
                key = event.which;
            }
            if (key == 13) {
                this.loginSubmit();
            }
        },
        getUserInfo: function () {
            var that = this;
            T.api("/user/info")
           .success(function (response) {
               if (response.ret === 0) {
                   var data = response.data;
                   //获取信息就退出登录
                   T.logout();
                   //用户数据 
                   $.ajax({
                       type: "POST",
                       url: "/Account/TencentWeibo_Login",
                       async: false,
                       cache: false,
                       data: {
                           openid: data.openid, sex: data.sex, nick: data.nick
                       },
                       dataType: "json",
                       success: function (result) {
                           if (AjaxValidate(result)) {
                               if (result.error == "0") {
                                   var bindPhoneModel = $.BENLAI.BindPhoneModel;
                                   var popFlag = 0;
                                   if (popFlag) {
                                       bindPhoneModel.CallBack = function () {
                                           if (loginModel.SuccessFunc) {
                                               that.closeLogin();
                                               loginModel.SuccessFunc();
                                           }
                                           else
                                               window.location.href = window.location.href;
                                           return false;
                                       };
                                   }
                                   else {
                                       var retrurnUrl = result.data ? result.data.ReturnUrl : "";
                                       bindPhoneModel.CallBack = function () {
                                           if (retrurnUrl) {
                                               window.location.href = decodeURIComponent(retrurnUrl);
                                               return false;
                                           } else {
                                               window.location.href = getLocationHref("/");
                                               return false;
                                           }
                                       };
                                   }
                                   that.LoginSuccess(result.data);
                               }
                               else {
                                   if (result.msg)
                                   {
                                       alert(result.msg);
                                   }
                               }
                           }
                       }
                   })
               } else {
                   //alert(response.ret);
               }
           })
          .error(function (code, message) {
              //alert(message);
          });
        },
        tenWeiboSub: function () {
            var that = this;
            T.login(function (loginStatus) {
                that.getUserInfo();
            }, function (loginError) {
                //alert(loginError.message);
            });
        },
        closeLogin: function () {
            $("#LoginTmpl").html("");
            $.BENLAI.LoginModel = null;
        },
        hideLogin: function ()
        {
            if ($.BENLAI.LoginModel.PopFlag == "1") {
                HideBack();
            }
            $("#loginDiv").hide();
        },
        LoginSuccess: function (data,popFlag) {
            if (data && data.BindPhoneTipType) {
                var bindPhoneModel = $.BENLAI.BindPhoneModel;
                if (data.LoginBranchType && data.LoginBranchType != 1) {
                    bindPhoneModel.NeedPass = true;
                }
                var BindPhoneTipType = data.BindPhoneTipType;
                if (popFlag) {
                    this.hideLogin();
                }
                if (BindPhoneTipType == 1) {
                    bindPhoneModel.CallBack();
                } else if (BindPhoneTipType == 2) {//must2
                    bindPhoneModel.SuccessMesFlag = true;
                    bindPhoneModel.SuccessMes = "您需要先进行手机绑定！";
                    bindPhoneModel.NeverTipFlag = false;
                    bindPhoneModel.MustBindFlag = 1;
                    bindPhoneModel.FirstBindFlag = data.BindPhoneFirstFlag;
                    bindPhoneModel.Score = data.Score > 0 ? data.Score : 0;
                    bindPhoneModel.CusToken = data.CusToken;
                    bindPhoneModel.Account = data.CustomerID;
                    bindPhoneModel.PopFlag = true;
                    
                    bindPhoneModel.showPage();
                } else if (BindPhoneTipType == 3) {
                    var bindPhoneModel = $.BENLAI.BindPhoneModel;
                    bindPhoneModel.SuccessMesFlag = true;
                    bindPhoneModel.SuccessMes = "您已登陆成功！";
                    bindPhoneModel.NeverTipFlag = true;
                    bindPhoneModel.FirstBindFlag = data.BindPhoneFirstFlag;
                    bindPhoneModel.Score = data.Score > 0 ? data.Score : 0;
                    bindPhoneModel.PopFlag = true;
                    bindPhoneModel.showPage();
                }
            }
        }
    });


});